<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{

    public function getUser(string $name)
    {
        $user = User::orWhere('name', $name);
        foreach (['email'] as $field) {

            $user->orWhere($field, $name);
        }
        return $user->first();
    }


    public function login(Request $request)
    {
        $user = $this->getUser($request->name);
        $request->validate([
            'name' => [
                'required',
                function ($attribute, $value, $fail) use ($user) {
                    if (!$user) {
                        $fail('The ' . $attribute . ' does not exist.');
                    }
                }
            ]
        ]);
        auth()->login($user, true);//保存用户
        return response()->json(['message' => 'Login successful'], 200);
    }


    public function logout() {}
}
